<?php

/** Socket 类库 
 * Copyright (c) 2012, Jiehun.com.cn Inc. All Rights Reserved
 * @author huqingping@jiehun.com.cn
 * @date 2013-05-02
 * @version 1.0 
 * @brief 
 *  
 **/

 final class Socket
 {
 	
	private $conf = null;
	private $connect = null;
	Const WRAP = "\n";

	/**
	*初始化配置
	* conf 元素介绍 ip:server ip port:端口号 time_out:超时时间(s) retry:连接失败重试次数
	*/
	function loadConfig($conf)
	{
		if(!$conf)
		{
			throw new Exception('Socket.EmptyConf');
		}
		$this->conf = $conf;
	}

	/**
	*建立socket连接
	*/
	function getConnect()
	{
		$timeOut = !empty($this->conf['time_out'])?$this->conf['time_out']:ini_get('default_socket_timeout');
		if(!$timeOut) $timeOut = 30;
		$timeOut = 2;
		$this->connect = fsockopen($this->conf['ip'],$this->conf['port'],$errno,$errstr,$timeOut);
		if(!$this->connect && !empty($this->conf['retry']))
		{
			for($i=0;$i<$this->conf['retry'];$i++)
			{
				if(!$this->connect)
				{
					$this->connect = @fsockopen($this->conf['ip'],$this->conf['port'],$errno,$errstr,$timeOut);
				}
			}
		}
		if(!$this->connect)
		{
			throw new Exception('Socket.connet_failed');
		}
	}

	private function getSendStr($data)
	{
		$str='';
		if(is_array($data))
		{
			foreach($data as $k=>$d)
			{
				$str .= $k.':'.$d.self::WRAP;
			}
		}else{
			$str = $data.self::WRAP;
		}
		return $str;
	}

	/**
	*发送数据
	*/
	function sendData($data)
	{
		$this->getConnect();
		$sendStr = $this->getSendStr($data)."EOF".self::WRAP;
		fwrite($this->connect,$sendStr);
	}

	/**
	*接收返回数据
	*/
	function getResponse()
	{
		if(!$this->connect) throw new Exception('Socket.connet_failed');
		$ret = "";
		while($l=fgets($this->connect))
		{
			if(strpos($l,'EOF')!==false)
			{
				break;
			}else{
				$l = str_replace("\n","",$l);
				$l && $ret .= $l;
			}
		}
		$this->close();
		return $ret;
	}

	/**
	*关闭连接
	*/
	function close()
	{
		if($this->connect) fclose($this->connect);
	}
 }
